<template>
	<mips-ticket
		v-if="value"
		:program-info.sync="value"
		@img-current-change="handleImageCurrentChange"
		@img-size-change="handleImageSizeChange"
		:material-group-options.sync="materialGroupOptions"
		:template-group-options.sync="templateGroupOptions"
		:img-options.sync="imgOptions"
		@getImageList="getImageList"
		@handleClickSaveGroup="handleClickSaveGroup"
		@uploadFiles="uploadFiles"
		@submitForm="submitForm"
		@deleteGroup="deleteGroup"
		@delete-component="handleDeleteComponent"
		@back="handleBack"
		@save="handleSave"
	/>
</template>

<script>
import { uploadCover } from '@/api/ips/command'
import {
	addTicketStyleList,
	updateTicketStyleList,
	getTicketStyleDetails,
} from '@/api/qbs/ticketStyle'
import { listDataset } from '@/api/system/dataset'
import { equals as deepEquals } from 'ramda'
import { getV, remove } from '@/utils/storage-util'
import {
	listMaterial as il,
	listMaterial as vl,
	listMaterial as fl,
	uploadMaterial,
	addMaterial,
	editMaterial,
} from '@/api/ips/material'
import {
	groupTree,
	delGroup,
	addGroup,
	editGroup,
	whetherMaterial,
} from '@/api/ips/group'
export default {
	name: 'Editor',
	data() {
		return {
			value: undefined,
			imgOptions: {
				imageList: [],
				current: 1,
				size: 6,
				total: 0,
				sizes: [6, 12, 24, 60, 120],
			},
			form: {},
			queryParams: {},
			materialGroupOptions: [],
			templateGroupOptions: [],
		}
	},
	created() {
		this.queryParams = this.$route.params //接受参数
		// this.form = JSON.parse(getV('TICKET_INFO'))
		console.log('this.$route.params ', this.$route.params)
		this.getImageList()
		this.getMaterialGroupTree()
		this.getTemplateGroupTree()
		if (!this.queryParams.id) {
			// 新增节目
			this.value = Object.assign(this.queryParams, {
				id: null,
				width: 600,
				height: 500,
				scale: 1.0,
				remarks: '',
				bgColor: '',
				bgImg: '',
				status: 0,
				bizIds: '',
				pages: [
					{
						id: 1,
						title: '场景1',
						duration: null,
						componentList: [],
						imgId: null,
						bgImg: '',
						bgColor: '#fff',
						customScript: '',
						datasetId: '',
						datasetName: '',
						datasetFields: '',
						datasetParams: '',
						interval: 10,
					},
				],
			})

			console.log('debug val=', this.value)
		} else {
			// 编辑节目
			this.value = this.queryParams
			this.value.scale = 1
			this.value.pages = JSON.parse(this.queryParams.layout)
			this.value.width = Number.parseInt(this.value.width)
			this.value.height = Number.parseInt(this.value.height)
		}
	},
	beforeDestroy() {
		remove('PROGRAM_INFO')
		remove('PREVIOUS_ROUTE')
	},
	methods: {
		// 保存素材
		submitForm(formList, currentId, currentName, type, isConvert) {
			for (let key in formList) {
				formList[key].groupId = currentId
				formList[key].groupName = currentName
				if (isConvert == '1') {
					formList[key].isConvert = isConvert
				}
				if (formList[key].id) {
					editMaterial(formList[key]).then((response) => {
						if (response.code === 0) {
							switch (response.data) {
								case 'image':
									this.msgSuccess(this.$t('addImageSuccess'))
									break
								case 'audio':
									this.msgSuccess(this.$t('addMedioSuccess'))
									break
								case 'medio':
									this.msgSuccess(this.$t('addAudioSuccess'))
									break
								case 'file':
									this.msgSuccess(this.$t('addFileSuccess'))
									break
							}
							switch (type) {
								case 'img':
									this.getImageList(currentId)
									break
								case 'video':
									this.getVideoList(currentId)
									break
								case 'pdf':
									this.getFileList(currentId)
									break
								case 'music':
									this.getAudioList(currentId)
									break
								case 'template':
									this.getTemplateList(currentId)
									break
							}
						} else {
							this.msgError(response.msg)
						}
					})
				} else {
					addMaterial(formList[key]).then((response) => {
						if (response.code === 0) {
							switch (response.data) {
								case 'image':
									this.msgSuccess(this.$t('addImageSuccess'))
									break
								case 'audio':
									this.msgSuccess(this.$t('addMedioSuccess'))
									break
								case 'medio':
									this.msgSuccess(this.$t('addAudioSuccess'))
									break
								case 'file':
									this.msgSuccess(this.$t('addFileSuccess'))
									break
							}
							switch (type) {
								case 'img':
									this.getImageList(currentId)
									break
								case 'video':
									this.getVideoList(currentId)
									break
								case 'pdf':
									this.getFileList(currentId)
									break
								case 'music':
									this.getAudioList(currentId)
									break
								case 'template':
									this.getTemplateList(currentId)
									break
							}
						} else {
							this.msgError(response.msg)
						}
					})
				}
			}
		},
		// 得到数据源列表
		getDatasetList() {
			listDataset({
				size: this.datasetOptions.size,
				current: this.datasetOptions.current,
			}).then((response) => {
				this.datasetOptions.datasetList = response.data
				this.datasetOptions.total = response.total
			})
		},
		handleImageCurrentChange: function(val, currentId, filter) {
			console.log('handleImageCurrentChange', val)
			this.imgOptions.current = val
			this.getImageList(currentId, filter)
		},
		handleDatasetCurrentChange: function(val) {
			console.log('handleTemplateCurrentChange', val)
			this.datasetOptions.current = val
			this.getDatasetList()
		},
		handleImageSizeChange: function(val, currentId, filter) {
			console.log('handleImageSizeChange', val)
			this.imgOptions.current = 1
			this.imgOptions.size = val
			this.getImageList(currentId, filter)
		},
		// 得到图片列表
		getImageList(fullPathId, name) {
			il({
				current: this.imgOptions.current,
				size: this.imgOptions.size,
				type: 'image',
				fullPathId: fullPathId,
				name: name,
			}).then((res) => {
				this.imgOptions.imageList = res.data.map((it) => {
					it.url =
						process.env.VUE_APP_BASE_API + (it.decodedUrl || it.originalUrl)
					return it
				})
				this.imgOptions.total = res.total
			})
		},
		handleClickSaveGroup(groupObj, callback) {
			const fun = groupObj.id ? editGroup : addGroup
			fun(groupObj)
				.then((_) => {
					this.$message({
						message: this.$t('saveSuccess'),
						type: 'success',
						showClose: true,
					})
					const groupDialogVisible = true
					callback(groupDialogVisible)
					this.getMaterialGroupTree()
					this.getTemplateGroupTree()
				})
				.catch((_) => {})
		},
		// 获取素材模板列表
		getTemplateGroupTree() {
			groupTree({ groupId: 49 }).then((response) => {
				this.templateGroupOptions = response.data
				this.groupDict = []
				const findChildren = (arr, list) => {
					for (let i = 0; i < arr.length; i++) {
						if (arr[i].id) {
							list.push(arr[i])
						}
						if (arr[i].children && arr[i].children.length) {
							findChildren(arr[i].children, list)
						}
					}
				}
				findChildren(this.templateGroupOptions, this.groupDict)
			})
		},
		// 获取素材分组列表
		getMaterialGroupTree() {
			groupTree({ groupId: 20 }).then((response) => {
				this.materialGroupOptions = response.data
				this.groupDict = []
				const findChildren = (arr, list) => {
					for (let i = 0; i < arr.length; i++) {
						if (arr[i].id) {
							list.push(arr[i])
						}
						if (arr[i].children && arr[i].children.length) {
							findChildren(arr[i].children, list)
						}
					}
				}
				findChildren(this.materialGroupOptions, this.groupDict)
			})
		},
		// 删除分组
		deleteGroup(data, type) {
			whetherMaterial(data.id).then((response) => {
				if (response.data > 0) {
					this.$message({
						message: '该分组包含素材无法删除',
						type: 'warning',
						showClose: true,
					})
					return false
				}
				this.$confirm(`确认要删除分组："${data.name}"吗?`, '警告', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
				})
					.then(function() {
						return delGroup(data.id)
					})
					.then(() => {
						this.getMaterialGroupTree()
						switch (type) {
							case 'img':
								this.getImageList()
								break
							case 'video':
								this.getVideoList()
								break
							case 'pdf':
								this.getFileList()
								break
							case 'music':
								this.getAudioList()
								break
							case 'template':
								this.getTemplateGroupTree()
								this.getTemplateList()
								break
						}
						this.msgSuccess('删除成功')
					})
					.catch(function() {})
			})
		},
		// 上传素材
		uploadFiles(param) {
			const formData = new FormData()
			formData.append('file', param.file)
			uploadMaterial({
				data: formData,
				headers: { Accept: '*/*', 'Content-Type': 'multipart/form-data' },
			}).then((res) => {
				if (res.code == 0) {
					param.onSuccess(res)
				} else {
					param.onError(err)
				}
			})
		},
		handleDatasetSizeChange: function(val) {
			console.log('handleTemplateSizeChange', val)
			this.datasetOptions.current = 1
			this.datasetOptions.size = val
			this.getDatasetList()
		},
		handleDeleteComponent({ component, index, confirmCallback }) {
			this.$confirm('确认要删除选择的组件吗?', this.$t('warning'), {
				confirmButtonText: this.$t('submitText'),
				cancelButtonText: this.$t('cancelText'),
				type: 'warning',
			})
				.then((_) => {
					confirmCallback()
				})
				.catch((_) => {})
		},
		handleBack() {
			this.jump()
		},
		/**
		 *
		 * @param data 节目数据
		 * @param blob 节目截图对象
		 * @param callback 回调函数
		 */
		async handleSave(data, blob, callback) {
			console.log(data, 'data')
			let jsonLayout =
				this.form.layout === undefined
					? JSON.stringify(data.pages)
					: this.form.layout
			console.log(jsonLayout)
			// let layout = JSON.parse(jsonLayout)
			this.form = data
			this.form.layout = jsonLayout
			if (!this.form.id) {
				await addTicketStyleList(this.form)
				this.jump()
			} else {
				await updateTicketStyleList(this.form)
				this.jump()
			}
		},
		jump() {
			this.$router.replace({
				name: 'TicketManage',
				params: this.queryParams,
			})
			// this.$router.replace('/ipsProgram/index') // 没有这个路径
		},
	},
}
</script>

<style lang="scss" scoped></style>
